package com.example.demo.leetcode.top100;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname _27合并两个有序链表
 * @description
 * @date 2023/06/10 10:38
 * <p>
 * ******************************************************
 */
public class _27合并两个有序链表 {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        // 虚拟节点
        ListNode dummy1 = new ListNode(-1);
        ListNode dummy2 = dummy1;
        ListNode p = list1;
        ListNode q = list2;

        while (p != null || q != null) {
            if (p == null) {
                dummy1.next = q;
                break;
            } else if (q == null) {
                dummy1.next = p;
                break;
            } else {
                if (p.val <= q.val) {
                    dummy1.next = p;
                    p = p.next;
                } else {
                    dummy1.next = q;
                    q = q.next;
                }
                dummy1 = dummy1.next;
            }


        }
        return dummy2.next;

    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
